package com.hustbaidu.hustmap;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class CommentManager {
	private static HustMapDBHelper dbHelper;
	private static SQLiteDatabase db;

	public CommentManager(Context context){
		dbHelper = new HustMapDBHelper(context.getApplicationContext());
		db = dbHelper.getReadableDatabase();
	}
	
	public static void init(Context context){
		dbHelper = new HustMapDBHelper(context.getApplicationContext());
		try {
			db = dbHelper.getWritableDatabase();
		} catch (Exception e) {
			// TODO: handle exception
			dbHelper.close();
			db = dbHelper.getWritableDatabase();
		}
		
	}

	/**
	 * 获取所有的评论信息
	 * @return 所有的评论信息的列表
	 */
	public static List<Comment> getAllComments(){
		List<Comment> list = new ArrayList<Comment>();
		Cursor cursor = db.query("comment", null, null, null, null, null, null);
		Comment comment = null;
		while(cursor.moveToNext()){
			comment = new Comment();
			comment.setId(cursor.getInt(cursor.getColumnIndex("_id")));
			comment.setUserName(cursor.getString(cursor.getColumnIndex("user_name")));
			comment.setContent(cursor.getString(cursor.getColumnIndex("content")));
			
			String time = cursor.getString(cursor.getColumnIndex("time"));
			try{
				comment.setTime(Timestamp.valueOf(time));
			}
			catch (Exception e) {
				e.printStackTrace();
			}
			
			comment.setPlace(cursor.getInt(cursor.getColumnIndex("place")));
			
			list.add(comment);
			
		}
		cursor.close();
		return list;
	}
	
	/**
	 * 根据地点的ID获取对应地点的评论信息
	 * @param placeId 地点的ID
	 * @return 对应地点的评论信息列表
	 */
	public static List<Comment> getAllComments(int placeId){
		List<Comment> list = new ArrayList<Comment>();
		Cursor cursor = db.query("comment", null, "place = ?", new String[]{String.valueOf(placeId)}, null, null, null);
		Comment comment = null;
		while(cursor.moveToNext()){
			comment = new Comment();
			comment.setId(cursor.getInt(cursor.getColumnIndex("_id")));
			comment.setUserName(cursor.getString(cursor.getColumnIndex("user_name")));
			comment.setContent(cursor.getString(cursor.getColumnIndex("content")));
			
			String time = cursor.getString(cursor.getColumnIndex("time"));
			try{
				comment.setTime(Timestamp.valueOf(time));
			}
			catch (Exception e) {
				e.printStackTrace();
			}
			
			comment.setPlace(cursor.getInt(cursor.getColumnIndex("place")));
			
			list.add(comment);
			
		}
		cursor.close();
		return list;
	}
	
	/**
	 * 根据地点的ID获取对应地点的评论数量
	 * @param placeId 地点的ID
	 * @return 对应地点的评论数量
	 */
	public static int getCommentNumberByPlace(int placeId){
		Cursor cursor = db.query("comment", null, "place = ?", new String[]{String.valueOf(placeId)}, null, null, null);
		int commentNum = cursor.getCount();
		cursor.close();
		return commentNum;
	}
}
